<script>
export default {
  name: 'DocShow',
  data() {
    return {
      // --- 新增：字体大小控制 ---
      fontSize: 16, // 默认 16px

      passage: {
        mainIdea: '本文是一篇说明文。主要介绍了中国原创玩具Labubu的外形特征、性格特点以及她的朋友们。',
        document: [
          {
            'paragraph': [
              {
                'sentence': 'Hello! I\'m Labubu.',
                'translation': '你好！我是Labubu。'
              },
              {
                'sentence': 'I am a small monster(怪兽).',
                'translation': '我是一只小怪兽。'
              },
              {
                'sentence': 'I\'m from China.',
                'translation': '我来自中国。'
              },
              {
                'sentence': 'I look like a rabbit.',
                'translation': '我看起来像一只兔子。'
              },
              {
                'sentence': 'I have two long ears and big eyes.',
                'translation': '我有两只长长的耳朵和大大的眼睛。'
              },
              {
                'sentence': 'There is always a funny smile on my face.',
                'translation': '我的脸上总是带着好笑的微笑。'
              },
              {
                'sentence': 'When I smile, you can see my long teeth too.',
                'translation': '当我微笑时，你也能看到我长长的牙齿。'
              },
              {
                'sentence': 'I\'m cute and kind.',
                'translation': '我可爱又善良。'
              },
              {
                'sentence': 'I have many friends.',
                'translation': '我有很多朋友。'
              },
              {
                'sentence': 'One of my friends is Zimomo.',
                'translation': '我的一个朋友是Zimomo。'
              },
              {
                'sentence': 'He looks like a rabbit too.',
                'translation': '他看起来也像一只兔子。'
              },
              {
                'sentence': 'He is a little quiet.',
                'translation': '他有点安静。'
              },
              {
                'sentence': 'Mokoko is my friend too.',
                'translation': 'Mokoko也是我的朋友。'
              },
              {
                'sentence': 'She is very kind.',
                'translation': '她非常善良。'
              },
              {
                'sentence': 'She has colourful fur(软毛).',
                'translation': '她有五颜六色的软毛。'
              },
              {
                'sentence': 'Many people like us.',
                'translation': '很多人喜欢我们。'
              },
              {
                'sentence': 'Because we\'re in the blind boxes.',
                'translation': '因为我们在盲盒里。'
              },
              {
                'sentence': 'You can enjoy the surprise(惊喜) of opening a box and getting a new toy.',
                'translation': '你可以享受打开盒子、得到新玩具的惊喜。'
              }
            ]
          }
        ]
      },
      activeParaIndex: -1,
      hoverParaIndex: -1,
      showMainIdea: false,

      // 提示框状态
      tooltip: {
        visible: false,
        x: 0,
        y: 0,
        arrowLeft: 0,
        placement: 'top',
        title: '',
        content: '',
        subContent: '',
        type: 'word'
      },

      // 句子高亮状态
      activeSentence: {
        docIndex: -1,
        range: null
      }
    }
  },
  created() {
    this.passage.document.forEach(doc => {
      const fullText = this.getParaSentences(doc.paragraph)
      doc.sentenceWords = fullText.split(' ')

      let currentIndex = 0
      doc.sentenceMap = doc.paragraph.map(item => {
        const wordCount = item.sentence.split(' ').length
        const range = {
          start: currentIndex,
          end: currentIndex + wordCount - 1,
          original: item.sentence,
          translation: item.translation
        }
        currentIndex += wordCount
        return range
      })
    })
  },
  mounted() {
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {
    toggleMainIdea() {
      this.showMainIdea = !this.showMainIdea
    },
    // --- 新增：设置预设字体 ---
    setFontSize(size) {
      this.fontSize = size
      // 调整字体后，如果 Tooltip 打开，位置可能会偏移，这里简单处理为关闭 Tooltip
      this.tooltip.visible = false
      this.activeSentence.range = null
    },

    toggleTranslation(index) {
      this.activeParaIndex = this.activeParaIndex === index ? -1 : index
    },
    getParaSentences(paraList) {
      return paraList.map(item => item.sentence).join(' ')
    },

    speakParagraph(index) {
      console.log(`正在朗读第 ${index} 段...`)
      const text = this.passage.document[index].paragraph.map(p => p.sentence).join(' ')
      const msg = new SpeechSynthesisUtterance(text)
      window.speechSynthesis.speak(msg)
    },

    handleWordClick(word, event) {
      this.activeSentence.range = null
      const cleanWord = word.replace(/[.,!?'"()]/g, '')
      this.tooltip.type = 'word'
      this.tooltip.title = cleanWord
      this.tooltip.content = `点击了单词 "${cleanWord}"`
      this.tooltip.subContent = '词性: Noun/Verb (示例)'
      this.showTooltip(event)
    },

    highlightOriginalSentence(docIndex, sentenceIndex) {
      const doc = this.passage.document[docIndex]
      const range = doc.sentenceMap[sentenceIndex]
      if (range) {
        this.activeSentence = {
          docIndex: docIndex,
          range: { start: range.start, end: range.end }
        }
      }
    },

    clearHighlight() {
      if (!this.tooltip.visible) {
        this.activeSentence.range = null
      }
    },

    handleWordDblClick(docIndex, wordIndex, event) {
      const doc = this.passage.document[docIndex]
      const targetSentence = doc.sentenceMap.find(range => {
        return wordIndex >= range.start && wordIndex <= range.end
      })

      if (targetSentence) {
        this.activeSentence = {
          docIndex: docIndex,
          range: { start: targetSentence.start, end: targetSentence.end }
        }
        this.tooltip.type = 'sentence'
        this.tooltip.title = '精读句子'
        this.tooltip.content = targetSentence.original
        this.tooltip.subContent = targetSentence.translation
        this.showTooltip(event)
      }
    },

    showTooltip(event) {
      this.tooltip.visible = true
      const target = event.target
      this.$nextTick(() => {
        this.smartPositionTooltip(target)
      })
    },

    smartPositionTooltip(target) {
      const tooltipEl = this.$el.querySelector('.word-tooltip')
      if (!tooltipEl || !target) return

      const targetRect = target.getBoundingClientRect()
      const tooltipRect = tooltipEl.getBoundingClientRect()
      const winWidth = window.innerWidth
      const winHeight = window.innerHeight
      const gap = 10
      const safePadding = 10

      let top = targetRect.top - tooltipRect.height - gap
      let placement = 'top'

      if (top < 0) {
        top = targetRect.bottom + gap
        placement = 'bottom'
      }

      if (placement === 'bottom' && (top + tooltipRect.height > winHeight)) {
        top = winHeight - tooltipRect.height - safePadding
      }

      const targetCenterX = targetRect.left + (targetRect.width / 2)
      let left = targetCenterX - (tooltipRect.width / 2)

      if (left < safePadding) left = safePadding
      if (left + tooltipRect.width > winWidth - safePadding) {
        left = winWidth - tooltipRect.width - safePadding
      }

      const arrowLeft = targetCenterX - left - 6

      this.tooltip.x = left
      this.tooltip.y = top
      this.tooltip.placement = placement
      this.tooltip.arrowLeft = arrowLeft
    },

    handleClickOutside() {
      this.tooltip.visible = false
      this.tooltip.currentWord = ''
      this.activeSentence.range = null
    },

    isWordInActiveSentence(dIndex, wIndex) {
      const active = this.activeSentence
      if (active.docIndex !== dIndex || !active.range) return false
      return wIndex >= active.range.start && wIndex <= active.range.end
    }
  }
}
</script>

<template>
  <div class="passage-card">
    <div class="toolbar">
      <div class="toolbar-font-size">
        <span class="toolbar-label">字体大小：</span>
        <div class="btn-group">
          <button class="size-btn" :class="{ active: fontSize === 16 }" @click="setFontSize(16)">小</button>
          <button class="size-btn" :class="{ active: fontSize === 20 }" @click="setFontSize(20)">中</button>
          <button class="size-btn" :class="{ active: fontSize === 24 }" @click="setFontSize(24)">大</button>
        </div>

        <div class="slider-group">
          <input
            type="range"
            min="14"
            max="32"
            step="1"
            v-model.number="fontSize"
            class="size-slider"
          >
          <span class="size-val">{{ fontSize }}px</span>
        </div>
      </div>

      <div>
        <button
          class="action-btn main-idea-btn"
          :class="{ active: showMainIdea }"
          @click="toggleMainIdea"
        >
          <span class="icon"><i class="fa-regular fa-lightbulb"></i></span>
          {{ showMainIdea ? '收起大意' : '主旨大意' }}
        </button>
      </div>
    </div>

    <div class="passage-content" :style="{ fontSize: fontSize + 'px' }">
      <transition name="fade">
        <div v-if="showMainIdea" class="main-idea-box">
          <span class="idea-tag">【主旨大意】：</span>
          {{ passage.mainIdea }}
        </div>
      </transition>

      <div v-for="(doc, docIndex) in passage.document" :key="docIndex">
        <div
          class="paragraph-item"
          @mouseenter="hoverParaIndex = docIndex"
          @mouseleave="hoverParaIndex = -1"
        >
          <div class="paragraph-text" :style="{ fontSize: fontSize + 'px' }">
            <span
              v-for="(word, wordIndex) in doc.sentenceWords"
              :key="wordIndex"
              class="word-span"
              :class="{
                'active-word': tooltip.visible && tooltip.type === 'word' && tooltip.title === word.replace(/[.,!?'\(\)]/g, ''),
                'sentence-highlight': isWordInActiveSentence(docIndex, wordIndex),
                'highlight-start': activeSentence.docIndex === docIndex && activeSentence.range && wordIndex === activeSentence.range.start,
                'highlight-end': activeSentence.docIndex === docIndex && activeSentence.range && wordIndex === activeSentence.range.end
              }"
              @click.stop="handleWordClick(word, $event)"
              @dblclick.stop="handleWordDblClick(docIndex, wordIndex, $event)"
            >
              <span v-if="wordIndex === 0" class="indent-spacer"/>
              {{ word }}
            </span>
          </div>

          <div
            class="para-actions"
            v-show="hoverParaIndex === docIndex || activeParaIndex === docIndex"
          >
            <button class="action-btn" @click.stop="toggleTranslation(docIndex)">
              <span class="icon"><i class="fa-solid fa-language"></i></span>
              {{ activeParaIndex === docIndex ? '收起翻译' : '段落翻译' }}
            </button>
            <button class="action-btn" @click.stop="speakParagraph(docIndex)">
              <span class="icon"><i class="fa-solid fa-volume-high"></i></span> 段落朗读
            </button>
          </div>

          <transition name="fade">
            <div
              v-if="activeParaIndex === docIndex"
              class="translation-container"
              :style="{ fontSize: fontSize + 'px' }"
            >
              <span
                v-for="(item, sIndex) in doc.paragraph"
                :key="sIndex"
                class="trans-sentence"
                @mouseenter="highlightOriginalSentence(docIndex, sIndex)"
                @mouseleave="clearHighlight"
              >
                {{ item.translation }}
              </span>
            </div>
          </transition>
        </div>
      </div>
    </div>

    <div
      v-show="tooltip.visible"
      class="word-tooltip"
      :class="tooltip.type"
      :data-placement="tooltip.placement"
      :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
      @click.stop
    >
      <div class="tooltip-header">{{ tooltip.title }}</div>
      <div class="tooltip-body">
        <p class="primary-text">{{ tooltip.content }}</p>
        <p v-if="tooltip.subContent" class="secondary-text">{{ tooltip.subContent }}</p>
      </div>
      <div v-if="tooltip.type === 'word'" class="tooltip-footer">
        <button class="sound-btn">🔊 发音</button>
      </div>
      <div class="tooltip-arrow" :style="{ left: tooltip.arrowLeft + 'px' }"/>
    </div>
  </div>
</template>

<style scoped>
.passage-card {
  background-color: #ffffff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* --- 新增：工具栏样式 --- */
.toolbar {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
  margin-bottom: 5px;
  gap: 16px;
  font-size: 14px;
  color: #333;
}

.toolbar-font-size {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toolbar-label {
  font-weight: bold;
  color: #555;
}

.main-idea-btn {
  font-weight: bold;
}

.main-idea-btn .icon {
  font-size: 16px;
}

/* --- 新增：主旨大意显示框样式 --- */
.main-idea-box {
  background-color: #fffbe6; /* 浅黄色背景 */
  border-left: 4px solid #faad14; /* 橙色左侧边框 */
  padding: 12px 16px;
  border-radius: 4px;
  margin-bottom: 5px;
  color: #594400;
  line-height: 1.6;
}

.idea-tag {
  font-weight: bold;
  color: #faad14;
  margin-right: 8px;
}

.btn-group {
  display: flex;
  gap: 8px;
}

.size-btn {
  padding: 4px 12px;
  border: 1px solid #d9d9d9;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.size-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.size-btn.active {
  background-color: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

.slider-group {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto; /* 将滑块推到右边 */
}

.size-slider {
  width: 100px;
  cursor: pointer;
  accent-color: #1890ff;
}

.size-val {
  font-family: monospace;
  width: 40px;
  text-align: right;
  color: #888;
}

.passage-content {
  /* 这里的 font-size: 16px 被移除，改为由 style 绑定控制 */
  color: #4a4a4a;
  line-height: 1.8;
}

.paragraph-item {
  padding: 16px 12px;
  border-radius: 8px;
  transition: background-color 0.2s ease;
  margin-bottom: 24px;
  border: 1px solid transparent;
}

.paragraph-item:hover {
  background-color: #fafafa;
  border-color: #eee;
}

.para-actions {
  margin-top: 12px;
  display: flex;
  gap: 10px;
  padding-top: 8px;
  border-top: 1px dashed #eee;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 13px; /* 按钮字体固定，不随滑块变化 */
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.action-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.action-btn .icon {
  font-size: 14px;
}

.paragraph-text {
  line-height: 2.4;
  text-align: justify;
  color: #333;
  /* font-size 由 inline-style 动态控制 */
  transition: font-size 0.2s ease; /* 添加过渡动画，让变大变小更顺滑 */
}

.translation-container {
  margin-top: 12px;
  padding: 12px;
  background-color: #f7f9fa;
  border-radius: 6px;
  color: #555;
  /* font-size 由 inline-style 动态控制 */
  line-height: 1.8;
  border-left: 3px solid #1890ff;
  transition: font-size 0.2s ease;
}

.trans-sentence {
  display: inline;
  cursor: pointer;
  padding: 0 2px;
  border-radius: 2px;
  transition: background-color 0.2s;
}

.trans-sentence:hover {
  background-color: #1890ff;
  color: #fff;
  font-weight: 500;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

/* --- 单词与交互样式 --- */
.word-span {
  display: inline-block;
  padding: 2px 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  user-select: none;
}

.word-span:hover {
  background-color: #e6f7ff;
  color: #096dd9;
  transform: scale(1.05);
}

.word-span.active-word {
  background-color: #1890ff;
  color: #fff;
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
}

.sentence-highlight {
  background-color: #1890ff !important;
  color: #fff !important;
  transform: none !important;
  border-radius: 0;
}

.sentence-highlight.highlight-start {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}

.sentence-highlight.highlight-end {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
}

.indent-spacer {
  display: inline-block;
  width: 20px;
}

/* --- Tooltip 样式 (固定字体大小，不随全局变化) --- */
.word-tooltip {
  position: fixed;
  z-index: 1000;
  background-color: #333;
  color: #fff;
  padding: 12px;
  border-radius: 8px;
  max-width: 500px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  font-size: 14px; /* 固定字体 */
  pointer-events: auto;
  transition: opacity 0.2s, top 0.1s, left 0.1s;
}

.word-tooltip.sentence {
  max-width: 700px;
  background-color: #222;
}

.tooltip-arrow {
  position: absolute;
  width: 0;
  height: 0;
  border-style: solid;
  left: 50%;
}

.word-tooltip[data-placement="top"] .tooltip-arrow {
  bottom: -6px;
  border-width: 6px 6px 0 6px;
  border-color: #333 transparent transparent transparent;
}

.word-tooltip.sentence[data-placement="top"] .tooltip-arrow {
  border-top-color: #222;
}

.word-tooltip[data-placement="bottom"] .tooltip-arrow {
  top: -6px;
  border-width: 0 6px 6px 6px;
  border-color: transparent transparent #333 transparent;
}

.word-tooltip.sentence[data-placement="bottom"] .tooltip-arrow {
  border-bottom-color: #222;
}

.word-tooltip.sentence .tooltip-arrow {
  border-top-color: #222;
}

.tooltip-header {
  font-weight: bold;
  font-size: 16px; /* 固定 */
  margin-bottom: 8px;
  border-bottom: 1px solid #555;
  padding-bottom: 4px;
}

.primary-text {
  font-size: 14px; /* 固定 */
  margin-bottom: 4px;
  line-height: 1.4;
}

.secondary-text {
  font-size: 13px; /* 固定 */
  color: #bbb;
  margin-top: 6px;
  padding-top: 6px;
  border-top: 1px dashed #444;
}

.tooltip-footer {
  margin-top: 8px;
  text-align: right;
}

.sound-btn {
  background: #1890ff;
  border: none;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.sound-btn:hover {
  background: #40a9ff;
}
</style>
